<?php
// +----------------------------------------------------------------------
// | sfadmin - Suifeng Administration
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2020 http://suifeng.tech All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: suifeng <1787585212@qq.com>
// +----------------------------------------------------------------------

namespace app\wechat\service;

use app\wechat\common\WechatException;

/**
 * 标签管理。
 */
final class Tag
{
    /**
     * 下载标签列表。
     * 该操作会先删除本地数据库的标签信息，用微信服务器上的数据取代。
     *
     * @param unknown $mp_number
     */
    public function download_tag_list($mp_number)
    {
        $download_time = time();

        model('wechat/user')->where('id', '>', 0)->update(array('tagid_list' => ''));

        $wxobj = service('wechat/mp')->get_wx_object($mp_number);

        $result = $wxobj->get_tag_list();
        if ($result === false) {
            throw new WechatException($wxobj);
        }

        if (isset($result['tags']) && $result['tags']) {
            foreach ($result['tags'] as $tag) {
                $tag_info = model('wechat/tag')->where(array('mp_number' => $mp_number, 'tagid' => $tag['id']))->find();
                if ($tag_info === null) {
                    $tag_info = model('wechat/tag')->initDefault();
                    $tag_info['mp_number'] = $mp_number;
                    $tag_info['tagid'] =  $tag['id'];
                }

                $tag_info['name'] =  $tag['name'];
                $tag_info['user_count'] =  $tag['count'];
                $tag_info['download_time'] =  $download_time;
                $tag_info->save();

                $this->download_tag_users($wxobj, $mp_number, $tag_info, $tag['id']);
            }
        }

        model('wechat/tag')->where('download_time', '<', $download_time)->delete();
    }

    private function download_tag_users($wxobj, $mp_number, $tag_info, $tag_id)
    {
        $next_openid = '';

        while (true) {
            $result = $wxobj->get_tag_users(array('tagid' => $tag_id, 'next_openid' => $next_openid));
            if ($result === false) {
                throw new WechatException($wxobj);
            }

            if (isset($result['data']['openid']) && $result['data']['openid']) {
                foreach ($result['data']['openid'] as $openid) {
                    $user_info = get_user_by_openid($mp_number, $openid);
                    $user_info['tagid_list'] = ($user_info['tagid_list'] ? ',' : '') . $tag_id;
                    $user_info->save();
                }
            }

            if (isset($result['next_openid']) && $result['next_openid']) {
                $next_openid = $result['next_openid'];
            } else {
                break;
            }
        }
    }

    public function create_tag($mp_number, $tag_name)
    {
        $wxobj = service('wechat/mp')->get_wx_object($mp_number);

        $result = $wxobj->create_tag(array('tag' => array('name' => $tag_name)));
        if ($result === false) {
            throw new WechatException($wxobj);
        }

        $tag_info = model('wechat/tag')->initDefault();
        $tag_info['mp_number'] = $mp_number;
        $tag_info['name'] =  $result['tag']['name'];
        $tag_info['tagid'] =  $result['tag']['id'];
        $tag_info->save();
    }

    public function update_tag($mp_number, $tag_id, $tag_name)
    {
        $wxobj = service('wechat/mp')->get_wx_object($mp_number);

        $result = $wxobj->update_tag(array('tag' => array('id' => $tag_id, 'name' => $tag_name)));
        if ($result === false) {
            throw new WechatException($wxobj);
        }

        $tag_info = model('wechat/tag')->where(array('mp_number' => $mp_number, 'tagid' => $tag_id))->find();
        if ($tag_info === null) {
            $tag_info = model('wechat/tag')->initDefault();
            $tag_info['mp_number'] = $mp_number;
            $tag_info['tagid'] =  $tag_id;
        }

        $tag_info['name'] =  $tag_name;
        $tag_info->save();
    }

    public function delete_tag($mp_number, $tag_id)
    {
        $wxobj = service('wechat/mp')->get_wx_object($mp_number);

        $result = $wxobj->delete_tag(array('tag' => array('id' => $tag_id, 'name' => $tag_name)));
        if ($result === false) {
            throw new WechatException($wxobj);
        }

        $tag_info = model('wechat/tag')->where(array('mp_number' => $mp_number, 'tagid' => $tag_id))->find();
        if ($tag_info !== null) {
            $tag_info->delete();
        }
    }

    public function batch_tagging($mp_number, $tag_id, $openid_list)
    {
        $wxobj = service('wechat/mp')->get_wx_object($mp_number);

        if (is_string($openid_list)) {
            $openid_list = array($openid_list);
        }

        $last_list = array();
        $list_array = array();

        foreach ($openid_list as $openid) {
            if (count($last_list) < 20) {
                $last_list[] = $openid;
            } else {
                $list_array[] = $last_list;
                $last_list = array($openid);
            }
        }

        if ($last_list) {
            $list_array[] = $last_list;
        }

        foreach ($list_array as $list) {
            $result = $wxobj->batch_tagging(array('tagid' => $tag_id, 'openid_list' => $list));
            if ($result === false) {
                throw new WechatException($wxobj);
            }

            foreach ($list as $openid) {
                $user_info = service('wechat/user')->get_user_by_openid($mp_number, $openid);
                $tagid_list = explode(',', $user_info['tagid_list']);
                if (($key = array_search($tag_id, $tagid_list)) !== false) {
                    unset($tagid_list[$key]);
                    $user_info['tagid_list'] = implode(',', $tagid_list);
                    $user_info->save();
                }
            }
        }
    }
}
